<template>
<!-- 这是登陆页面 -->
  <div id="login">
      <div class="login_title">
        <router-link to="/"><img src="../../../public/img/logo10.png" alt=""></router-link>
      </div>
      <div class="login_tabs">
        <h3>{{$t("Login.title")}}</h3>
        <div class="dialog_title">
          <div class="weixin"><span @click="loginWX"></span></div>
          <div class="qq"><span></span></div>
        </div>
        <el-tabs v-model="activeName" type="card" @tab-click="handleClick">
          <el-tab-pane :label="$t('Login.accountLogin')" name="account">
            <div class="login">
              <el-form :model="ruleForm" ref="account" label-width="100px" class="login-ruleForm login_one" :rules="rules" status-icon>
                      <el-form-item prop="userMobile">
                        <div class="iconFather">
                          <span class="el-icon-s-custom"></span>
                          <el-input type="string" v-model="ruleForm.userMobile" :placeholder="$t('share.rules.userMobile')"  maxlength="22"></el-input>
                        </div>
                      </el-form-item>
                      <el-form-item prop="userPassword">
                        <div class="iconFather">
                          <span class="el-icon-lock"></span>
                          <el-input type="password" v-model="ruleForm.userPassword" autocomplete="off" :placeholder="$t('share.rules.userPassword')" maxlength="12"></el-input>
                        </div>
                      </el-form-item>
                      <el-form-item>
                          <el-checkbox v-model="checked">{{$t("Login.checked")}}</el-checkbox>
                      </el-form-item>
              </el-form>
            </div> 
          </el-tab-pane>
          <el-tab-pane :label="$t('Login.phoneLogin')" name="phone">
            <div class="login">
              <el-form :model="phoneRuleForm" ref="phone" label-width="100px" class="login-ruleForm" :rules="phoneRules" status-icon>
                      <el-form-item prop="userPhone">
                        <div class="iconFather">
                          <span class="el-icon-mobile-phone"></span>
                          <el-input type="string" v-model="phoneRuleForm.userPhone" :placeholder="$t('share.rules.userPhone')"  maxlength="11"></el-input>
                        </div>
                      </el-form-item>
                      <el-form-item prop="phoneCode" class="verificationCode">
                        <div class="iconFather">
                          <span class="el-icon-chat-dot-square"></span>
                          <el-input type="string" v-model="phoneRuleForm.phoneCode" class="codeInput" :placeholder="$t('share.rules.verificationCode')" maxlength="8"></el-input>
                          <div class="code"><button @click.prevent="phoneCode('phone')" :disabled="codeBool">{{verificationCode}}</button></div>
                        </div>
                      </el-form-item>
              </el-form>
            </div>
          </el-tab-pane>
        </el-tabs>
        <el-button type="primary" :loading="loading" @click="submitForm(`${tabsName}`)">{{$t("Login.login2")}}</el-button>
        <div class="standby"><div class="standbyPass"><a>{{$t("Login.standbyPass")}}</a></div><div class="standbyId"><a @click="register()">{{$t("Login.account")}}</a></div></div>
      </div>
      <div class="login_bottom">
        <div class="container">
          <div class="row">
            <div class="col-md-12 text-center">
              <ul class="social">
                <li class="wow bounceIn">
                  <a href="javascript:void(0);">
                    <i class="fa fa-facebook"></i>
                  </a>
                </li>
                <li class="wow bounceIn" data-wow-delay="0.1s">
                  <a href="javascript:void(0);">
                    <i class="fa fa-twitter"></i>
                  </a>
                </li>
                <li class="wow bounceIn" data-wow-delay="0.2s">
                  <a href="javascript:void(0);">
                    <i class="fa fa-dribbble"></i>
                  </a>
                </li>
                <li class="wow bounceIn" data-wow-delay="0.3s">
                  <a href="javascript:void(0);">
                    <i class="fa fa-behance"></i>
                  </a>
                </li>
                <li class="wow bounceIn" data-wow-delay="0.4s">
                  <a href="javascript:void(0);">
                    <i class="fa fa-pinterest"></i>
                  </a>
                </li>
                <li class="wow bounceIn" data-wow-delay="0.5s">
                  <a href="javascript:void(0);">
                    <i class="fa fa-google"></i>
                  </a>
                </li>
              </ul>
              <div class="bottom_text"><a href="http://www.beian.miit.gov.cn/" target="_blank">粤ICP备18151619号</a><i class="nbsp"></i><i class="nbsp"></i>广州市优粤家科技有限公司<i class="nbsp"></i>版权所有</div>
            </div>
          </div>
        </div>
      </div>
      <el-dialog :title="$t('share.rules.scanning')" center :visible.sync="dialogTableVisible" @close = "close">
        <div id="qrcode" ref="qrcode" ></div>
      </el-dialog>
  </div>
</template>

<script>
import QRCode from "qrcodejs2";  // 引入qrcode
let Base64 = require("js-base64").Base64;
export default {
data() {
    // 密码验证
    var validatePhone = (rule, value, callback) => {
      if (value === "") {
        callback(new Error(this.$t("share.rules.userPhone")));
      } else {
        callback();
      }
    };
    return {
      // WXQQTitle: "请使用微信扫描二维码",  //微信，QQ登录提示文字
      verificationCode: this.$t("share.rules.phoneCode"), //获取验证码
      WXflag: true, //是否进入计时器请求数据
      WXtimer: null,  //setInterval计时器
      Phonetimer: null, //手机验证码计时器
      Phoneflag: true,  //手机验证码是否进入计时器
      activeName: "account",  //默认标签页是哪个
      tabsName: "account",  //切换的name标识
      codeBool: false,  //是否禁用按钮
      checked: false, // 记住密码状态
      loading: false, // 提交时加载状态
      dialogTableVisible: false,  //是否显示二维码
      ruleForm: {
        userMobile: "", //账号
        userPassword: "", //密码
      },
      phoneRuleForm: {
        userPhone: "",  //手机号码
        phoneCode: "",  //手机验证码
      },
      // 手机登陆验证
      phoneRules: {
        userPhone: [
          { required: true, validator: validatePhone, trigger: "blur" },
          { pattern: /^1(3|4|5|6|7|8|9)\d{9}$/, message: this.$t("share.rules.errorPhone"),trigger: "blur"}
        ],
        phoneCode: [
          { required: true, message: this.$t("share.rules.verificationCode"), trigger: "blur" },
          { pattern: /^\d{5,8}$/, message: this.$t("share.rules.errorCode"),trigger: "blur"}
        ],
      },
      // 账号登录验证
      rules: {
        userMobile: [
          { required: true, message: this.$t("share.rules.userMobile"), trigger: "blur" },
          { pattern: /^[a-zA-Z0-9@.]{4,22}$/, message: this.$t("share.rules.errorMobile"),trigger: "blur"}
        ],
        userPassword: [
          { required: true, message: this.$t("share.rules.userPassword"), trigger: "blur" },
          {required: true, pattern: /^[a-zA-Z0-9]{6,12}$/, message: this.$t("share.rules.userPasswordLength"),trigger: "blur"},
        ],
      },
    };
  },
  methods: {
    // 登陆
    submitForm(ruleForm) {
      var _this=this;
      let user = _this.ruleForm.userMobile;   //用户名
      let pass = Base64.encode(_this.ruleForm.userPassword);  //密码
      if(_this.tabsName == "account") {
        // 账号登录
        _this.$refs[ruleForm].validate((valid) => {
          if (valid) {
            _this.$post("user/login",{
              username: user,
              password: pass,
              type: "username",
            }).then(res=>{
              if(res.code == 200) {
                let expires_in = res.data.token.expires_in; //储存时间
                // 判断是否记住账号密码
                if(_this.checked){
                    // cookie储存，存储时间为7天
                    _this.$Cookie.setCookie("checked", _this.checked, { maxAge: expires_in });
                }else{
                  _this.$Cookie.removeCookie("checked");
                }
                _this.$Cookie.setCookie("userID", res.data.userInfo.user_id, { maxAge: expires_in });
                _this.$Cookie.setCookie("userMobile", Base64.encode(user), { maxAge: expires_in });
                _this.$Cookie.setCookie("userPassword", pass, { maxAge: expires_in });
                _this.$Cookie.setCookie("token", Base64.encode(res.data.token.access_token), { maxAge: expires_in });
                _this.$Cookie.removeCookie("strData");
                // 请求后台购物车的数据
                _this.$get(`cart/${res.data.userInfo.user_id}`
                ).then(res => {
                  if( res.code == 200) {
                    let headerArr = res.data;
                    let storeArr = _this.$store.state.goodNum;
                    let dataArr = headerArr.concat(storeArr);
                    let list = "";
                    const storeMap = new Map();
                    list = dataArr.filter((dataArr) => !storeMap.has(dataArr.goods_id) && storeMap.set(dataArr.goods_id, 1));
                    _this.$store.commit("goods", list);
                  }
                })
                // 获取用户信息，等级
                _this.getLevel(res.data.userInfo.user_id);
                // 消息提示
                _this.$MessageAlert(true,_this.$t("Login.loginSuccess"),"success");
                _this.$refs[ruleForm].resetFields();
                _this.$router.push({"path":"/"})
              } else if(res.code == 404) {
                _this.$MessageAlert(true,_this.$t("Login.loginError1"),"error");
              } else {
                _this.$MessageAlert(true,res.data,"error");
              }
            })
          } else {
            return false;
          }
        });
      } else if(_this.tabsName == "phone") {
        // 手机登录
        _this.$refs[ruleForm].validate((valid) => {
          if(valid) {
              _this.$post("user/login", {
                phone: _this.phoneRuleForm.userPhone,
                captcha: _this.phoneRuleForm.phoneCode,
                type: "phone",
              }
              ).then(res => {
                if(res.code == 200) {
                  _this.$Cookie.removeCookie("userPassword");
                  _this.$Cookie.removeCookie("checked");
                  _this.$Cookie.setCookie("userID", res.data.userInfo.user_id, { maxAge: res.data.token.expires_in });
                  _this.$Cookie.setCookie("userMobile", Base64.encode(res.data.userInfo.username), { maxAge: res.data.token.expires_in });
                  _this.$Cookie.setCookie("token", Base64.encode(res.data.token.access_token), { maxAge: res.data.token.expires_in });
                  clearInterval(_this.Phonetimer);  //清除手机验证码的计时器
                  _this.Phonetimer = null;    //清空手机验证码的计时器
                  _this.verificationCode = _this.$t("share.rules.phoneCode");   //赋值获取验证码按钮
                  // 请求后台购物车的数据
                  _this.$get(`cart/${res.data.userInfo.user_id}`
                  ).then(res => {
                    if( res.code == 200) {
                      let headerArr = res.data;
                      let storeArr = _this.$store.state.goodNum;
                      let dataArr = headerArr.concat(storeArr);
                      let list = "";
                      const storeMap = new Map();
                      list = dataArr.filter((dataArr) => !storeMap.has(dataArr.goods_id) && storeMap.set(dataArr.goods_id, 1));
                      _this.$store.commit("goods", list);
                    }
                  })
                  // 获取用户信息，等级
                  _this.getLevel(res.data.userInfo.user_id);
                  _this.$MessageAlert(true,_this.$t("Login.loginSuccess"),"success");
                  _this.$refs[ruleForm].resetFields();
                  _this.$router.push({"path":"/"})
                }
              })
          }
        });
      }
    },
    // 生成二维码
    qrcode(data) {
      new QRCode("qrcode", {
        width: 200,  
        height: 200,
        text: data, // 二维码地址
        correctLevel: QRCode.CorrectLevel.Q,  //降低检验级别
      })
      document.getElementById("qrcode").removeAttribute ("title");
      // $("#qrcode").removeAttr("title");
    },
    // 获取用户信息，等级
    getLevel(id) {
      var _this = this;
      // 获取用户信息，等级 null 为普通用户 1 为vip
      if(_this.$Cookie.getCookie("userLevel") === undefined) {
        _this.$get(`user/info/${id}`
        ).then(res => {
          if(res.code == 200) {
            _this.$Cookie.setCookie("userLevel", res.data.level, {maxAge: 604800 });     // 7天秒数
          }
        })
      }
    },
    // 微信登陆
    loginWX() {
      var _this = this;
      let strData = JSON.stringify(new Date().getTime()) + JSON.stringify(Math.round(Math.random()*100000000));
      let data = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx57e5163ce8035100&redirect_uri=https%3A%2F%2Fapi.shop.uekea.com%2FweChatLogin&response_type=code&scope=snsapi_userinfo&state=${strData}#wechat_redirect`
      _this.dialogTableVisible = true;
      // 调用二维码
      _this.$nextTick (function () {
        _this.qrcode(data);
      })
      if(_this.WXflag) {
        _this.WXtimer = setInterval(function() {
          // 获取微信授权后的用户信息
          _this.$get("user/weChatUserInfo").then(res => {
            if(res.openid !== undefined) {
              clearInterval(_this.WXtimer);   // 清除计时器
              _this.WXtimer = null;   // 清空计算器
              _this.WXflag = true;  // 重新赋值

              _this.close();  //调用关闭二维码弹框方法
              // 请求后台购物车的数据
              _this.$get(`cart/${res.openid}`
              ).then(res => {
                if( res.code == 200) {
                  let headerArr = res.data;
                  let storeArr = _this.$store.state.goodNum;
                  let dataArr = headerArr.concat(storeArr);
                  let list = "";
                  const storeMap = new Map();
                  list = dataArr.filter((dataArr) => !storeMap.has(dataArr.goods_id) && storeMap.set(dataArr.goods_id, 1));
                  _this.$store.commit("goods", list);
                }
              })
              // 获取用户信息，等级
              _this.getLevel(res.openid);

              _this.$Cookie.removeCookie("userPassword");
              _this.$Cookie.removeCookie("checked");
              _this.$Cookie.setCookie("userID", res.openid, { maxAge: 604800 });     // 7天秒数
              _this.$Cookie.setCookie("userMobile", Base64.encode(res.nickname), { maxAge: 604800 });
              _this.$Cookie.setCookie("token", Base64.encode(res.access_token), { maxAge: 604800 });
              _this.$Cookie.setCookie("strData", Base64.encode(strData), { maxAge: 604800 });
              _this.$store.commit("header", {nameBool: false, userName: res.nickname, openid: res.openid});  //用户名，openid,储存到vuex
              _this.$router.push({"path": "/"});
            }
          })
        },2500);
      } 
    },
    // QQ登陆
    // loginQQ() {
    //   console.log("");
    // },
    // 关闭dialog对话框
    close() {
      this.dialogTableVisible = false;
      this.$refs.qrcode.innerHTML = "";
      clearInterval(this.WXtimer);
      this.WXflag = true;
      this.WXtimer = null;
    },
    // 跳转到注册页面    
    register(){
      this.$router.push({"path":"/Register"});
    },
     // 标签页切换
    handleClick(tab) {
      var _this = this;
      if(tab.name == "account") {
        // 账号登陆
        _this.tabsName = "account";
        _this.$refs["phone"].resetFields();
      } else if(tab.name == "phone") {
        // 手机登陆
        _this.tabsName = "phone";
        if(!(_this.checked && _this.$Cookie.getCookie("userMobile") && _this.$Cookie.getCookie("userPassword"))) {
          _this.ruleForm.userMobile = "";
          _this.ruleForm.userPassword = "";
          _this.checked = false;  //是否记住密码
          _this.$refs["account"].resetFields();
        }
      }
    },
    // 获取手机短信验证码
    phoneCode(ruleForm) {
      var _this = this;
      _this.codeBool = true;
      let time = 60;
      // let flag = true;
      // 只验证手机是否有输入，部分验证，不是全部验证
      _this.$refs[ruleForm].validateField("userPhone", valid => {
        if(!valid) {
            // 倒计时
            if(_this.Phoneflag){
              // 请求验证码
              _this.$get(`user/sendSms/${_this.phoneRuleForm.userPhone}`
              ).then(res => {
                if( res.code == 200) {
                  _this.$MessageAlert(true, _this.$t("share.rules.succSend"),"success");
                } else {
                  _this.$MessageAlert(true, _this.$t("share.rules.errSend"),"error");
                }
              }).catch( ()=> {
                _this.codeBool = false;
              });
              // 倒计时
              _this.Phonetimer = setInterval(function() {
                  _this.Phoneflag = false;
                  _this.codeBool = true;
                  if(time == 0){
                      _this.verificationCode = _this.$t("share.rules.phoneCode");
                      clearInterval(_this.Phonetimer);
                      time = 60;
                      _this.Phoneflag = true;
                      _this.codeBool = false;
                  }else {
                      _this.verificationCode = time + " s "+_this.$t("share.rules.Resend");
                      time--;
                  }
              },1000);
            }
        } else {
          _this.codeBool = false;
        }
      });
    },
  },
  created() {
    var _this = this;
    if(_this.$Cookie.getCookie("checked") != undefined){
      _this.ruleForm.userMobile = Base64.decode(_this.$Cookie.getCookie("userMobile"));
      _this.ruleForm.userPassword = Base64.decode(_this.$Cookie.getCookie("userPassword"));
      _this.checked = true;
    }
  },
  beforeDestroy() {
    var _this = this;
    // 微信二维码弹框
    if(_this.$refs.qrcode != undefined) {
      clearInterval(_this.WXtimer);   //清除微信请求服务器的计时器
      _this.WXflag = true;
      _this.WXtimer = null;
      _this.$refs.qrcode.innerHTML = ""; //清空微信二维码弹框内容
    }
    // 登陆的手机验证码
    if(_this.Phonetimer != null) {
      clearInterval(_this.Phonetimer);  //清除手机验证码的计时器
      _this.Phonetimer = null;    //清空手机验证码的计时器
      _this.Phoneflag = true;     //手机验证码重新赋值
    }
    _this.dialogTableVisible = false;  //关闭微信二维码弹框
    _this.$refs["phone"].resetFields();   //清除输入框内容
    _this.$refs["account"].resetFields();
  }
}
</script>

<style lang="less" scoped>
@media screen and (max-width: 600px) {
  #login .login {
    font-size: 12px !important;
    flex-wrap: wrap;
    margin: auto 20px !important;
  }
}
@media screen and (max-height: 770px) {
  #login{
    height: 770px !important;
  }
}
// 微信，qq登陆
.weixin {
  display: inline-block;
  margin-right: 32px;
  span {
    width: 45px;
    height: 45px;
    border-radius: 50%;
    display: inline-block;
    background: url("../../../public/img/fouricon.png") -51px 0px no-repeat;
    background-size: 215%;
    cursor:pointer;
  }
  span:hover {
    background: url("../../../public/img/fouricon.png") -51px -52px no-repeat;
    background-size: 215%;
  }
}
.qq {
  display: inline-block;
  span {
    width: 45px;
    height: 45px;
    border-radius: 50%;
    display: inline-block;
    background: url("../../../public/img/fouricon.png") -3px 0px no-repeat;
    background-size: 215%;
    cursor:pointer;
  }
  span:hover {
    background: url("../../../public/img/fouricon.png") -3px -52px no-repeat;
    background-size: 215%;
  }
}
// 微信，qq登陆结束
.iconFather {
  position: relative;
}
.el-icon-s-custom,.el-icon-lock,.el-icon-mobile-phone,.el-icon-chat-dot-square{
  font-size: 22px;
  position: absolute;
  top: 9px;
  left: 11px;
  z-index: 1;
  color: #888;
}
.el-button{
  display: block;
  font-size: 20px;
  margin: auto;
  letter-spacing:2px;
  margin-top: 15px;
  background-color: transparent;
  border: 1px solid black;
  border-radius: 0px;
  color: black;
}
.el-button:hover {
  background-color: black;
  border: 1px solid black;
  color: white;
}
.el-button--primary:focus {
  background-color: black;
  border: 1px solid black;
}
.standbyPass {
  margin-bottom: 3px;
}
.standbyPass,.standbyId{
  font-size: 14px;
  text-decoration:underline;
  a {
    color: #409EFF;
  }
}
/deep/ .el-tabs__header {
  margin: 0px;
}
/deep/ .el-tabs--card>.el-tabs__header {
      border-bottom: 1px solid #ccc;
}
/deep/ .el-tabs__nav {
      border-top: 1px solid #ccc !important;
      border-left: 1px solid #ccc !important;
      border-right: 1px solid #ccc !important;
      border-radius: 0px !important;
}
/deep/ .el-tabs__item {
  border-left: 1px solid #ccc !important;
}
/deep/ .el-tabs__item:first-child {
  border-left: none !important;
}
#login {
  height: 100vh;
  display: flex;
  position: relative;
  flex-direction: column;
  background: url("../../../public/img/header.jpg") 0px 0px no-repeat;
  background-size: cover;
  .login_tabs {
    width: 450px;
    margin: 0px auto;
    border: 1px solid black;
    border-radius: 2px;
    padding: 25px;
    h3{
      font-size: 16px;
      letter-spacing:2px;
      color: black;
      margin-top: 0px;
    }
    /deep/ .dialog_title{
      text-align: center;
      margin-bottom: 20px;
      margin-top: 20px;
    }
  }
  .login_title{
    margin: 0px auto;
    display: inline-block;
    a {
      img {
        height: 100px;
      }
    }
    
  }
  .login {
    margin: auto;
    margin-top: 0px;
    border: 1px solid #ccc;
    border-top: 0px;
    padding: 0px 35px;
    display: flex;
    flex-direction: column;
    .login-ruleForm{
      position: relative;
      margin-top: 30px;
      margin-bottom: 20px;
    }
    .login_one {
      margin-bottom: 0px;
    }
  }
  /deep/ .el-form-item__content{
    margin: 0px !important;
    line-height: 25px;
  }
  /deep/ .el-input input{
    // text-indent: 1.3em;
    padding-left: 45px;
  }
  .verificationCode {
    // width: 180px;
    .code {
      border: 1px solid #DCDFE6;
      color: #555;
      line-height: 38px;
      width: 120px;
      text-align: center;
      float: right;
      border-radius: 5px;
      button:hover {
        cursor:pointer;
      }
    }
    .codeInput {
      width: 180px;
      display: inline-block;
    }
  }
}
.login_bottom {
  position: absolute;
  bottom: 0px;
  width: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  padding: 40px;
  color: white;
  .social {
    display: flex;
    justify-content: center;
    li {
      width: 30px;
      height: 30px;
      line-height: 30px;
      margin: 0px 5px;
      border-radius: 50%;
      overflow: hidden;
      transition-duration: 0.4s;
      i {
        width: 30px;
        height: 30px;
        line-height: 30px;
        font-size: 17px;
        color: white;
      }
    }
    li:hover {
      transition-duration: 0.4s;
      background-color: white;
      i {
        color: black;
      }
    }
  }
  .bottom_text {
    margin-top: 20px;
    .nbsp {
      padding:0px 5px;
    }
    a {
      font-weight: 100;
    }
    a:visited { 
      color: white; 
      text-decoration: none;
    }
  }
}
/deep/ .el-dialog {
  width: 380px;
  height: 360px;
  margin-top: 18vh;
}
/deep/ .el-dialog__body {
  text-align: center !important;
  padding: 30px !important;
  margin-top: 10px;
}
#qrcode {
  display: inline-block;
}
</style>